package com.xcl.interceptor;

import com.xcl.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //放行所有的预检请求   OPTIONS
        //request.getMethod()
        if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        //1，获取到token
        String token = request.getHeader("Authorization");
        try{

            System.out.println("拦截器拦截请求，获取的token："+token);
            Map<String,Object> claims =  JwtUtil.parseToken(token);


            //2,验证token 通过了  放行请求  return true
            return true;
        }catch (Exception e){
            //3,token验证失败
            response.setStatus(401);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"无效的token");
            //不通过 请求不放行  return false
            return false;
        }




    }
}
